import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

/**
 * 导出表格到 Excel 文件
 *
 * @param elt 表格的 DOM 元素
 * @param sheetName 内部 sheet 名称
 * @param fileName 导出的文件名
 * @param numCols 标题行数
 */
export const exportTable1 = (elt, sheetName, fileName, numCols) => {
    const workbook = XLSX.utils.book_new();
    const worksheet = XLSX.utils.table_to_sheet(elt);
    XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);

    // 设置列宽和样式
    const range = XLSX.utils.decode_range(worksheet['!ref']);
    const cWidth = [];
    const borderStyle = {
        top: { style: 'thin', color: { rgb: '000000' } },
        bottom: { style: 'thin', color: { rgb: '000000' } },
        left: { style: 'thin', color: { rgb: '000000' } },
        right: { style: 'thin', color: { rgb: '000000' } }
    };

    for (let C = range.s.c; C <range.e.c; ++C) {
        let maxLength = 10; // 默认最小列宽
        for (let R = range.s.r; R <= range.e.r; ++R) {
            const cellAddress = XLSX.utils.encode_cell({ c: C, r: R });
            const cell = worksheet[cellAddress];
            if (cell) {
                const cellValue = cell.v ? cell.v.toString() : '';
                const length = cellValue.length * (/[^\x00-\xff]/.test(cellValue) ? 2 : 1); // 中文字符宽度为2，其他字符宽度为1
                if (length > maxLength) maxLength = length;

                // 设置单元格样式
                cell.s = {
                    alignment: { horizontal: 'center', vertical: 'center' },
                    border: borderStyle
                };
                if (R < numCols) {
                    cell.s.font = { bold: true };
                    cell.s.fill = { fgColor: { rgb: 'E4E4E4' } };
                }
            }
        }
        cWidth.push({ wch: maxLength });
    }
    worksheet['!cols'] = cWidth;

    // 删除最后一列
    const lastColumnIndex = range.e.c;
    delete worksheet[XLSX.utils.encode_col(lastColumnIndex)];

    // 更新引用范围
    range.e.c--; // 减少一列，更新结束的列索引
    worksheet['!ref'] = XLSX.utils.encode_range(range);
    // 写入文件
    const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' });
    saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), `${fileName}.xlsx`);
};

function s2ab(s) {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i < s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
    return buf;
}
